
const express = require('express')
const app = express()
const cors = require('cors')
const userRouter = require('./router/user.js')
const joi = require('joi')
const userinfoRouter = require('./router/userinfo.js')
const scheduleRouter = require('./router/schedule.js')
const forgotRouter = require('./router/forgot.js');
app.use(cors())
app.use((req, res, next) => {
  res.cc = function (err, status = 1) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err
    })
  }
  next()
})

app.use(express.json());
const expressJWT = require('express-jwt')
const config = require('./schema/config.js')
const artCateRouter = require('./router/artcate.js')
const articleRouter = require('./router/article.js')
const meetingRouter = require('./router/meeting.js')
const memorygRouter = require('./router/memory.js')
const consumptionRouter = require('./router/comsumption.js')
const stressRouter = require('./router/stress.js')
const growthStoryRouter = require('./router/growth_story.js')
const markScheduleCompletedRouter = require('./router/markScheduleCompleted.js')
const dailySummaryRouter = require('./router/daily_summary.js')
app.use(express.urlencoded({ extended: false }))
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api/] }))
app.use('/api', userRouter)
app.use('/my', userinfoRouter)
app.use('/my/article', artCateRouter)
app.use('/my/article', articleRouter)
app.use('/my/schedule', scheduleRouter)
app.use('/my/meeting', meetingRouter)
app.use('/my/consumption', consumptionRouter)
app.use('/my/memory', memorygRouter)
app.use('/my/stress', stressRouter)
app.use('/api/growthStory', growthStoryRouter)
app.use('/my/markScheduleCompleted', markScheduleCompletedRouter)
app.use('/my/dailySummary', dailySummaryRouter);
app.use('/api', forgotRouter);
app.use((err, req, res, next) => {
  if (err instanceof joi.ValidationError) return res.cc(err)
  if (err.name === 'UnauthorizedError') return res.cc('身份认证失败')

})
app.listen(3007, function () {
  console.log('api server running at http://127.0.0.1:3007')
}) 